package com.etalk.crm.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.etalk.crm.dao.LessonsMapper;
import com.etalk.crm.pojo.*;
import com.etalk.crm.service.LessonsService;
import com.etalk.crm.service.StuDynamicService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Jordan
 */
@Service
public class LessonsServiceImpl implements LessonsService {

    @Resource
    private LessonsMapper lessonsMapper;
    @Resource
    private StuDynamicService stuDynamicService;
    @Resource
    private HttpServletRequest request;

    /**
     * 查询用户已预约的课程
     * @param personId 学员id
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 结果
     */
    @Override
    public PageInfo<StudentLesson> searchBookedList(Integer personId, int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<StudentLesson> list=lessonsMapper.selectStudentBookedLessonListByPersonId(personId);

        return new PageInfo<>(list);
    }

    /**
     * 查询用户已完成的课程
     * @param personId 学员id
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 结果
     */
    @Override
    public PageInfo<StudentLesson> searchCompletedList(Integer personId, int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<StudentLesson> list=lessonsMapper.selectStudentCompletedLessonListByPersonId(personId);
        return new PageInfo<>(list);
    }

    /**
     * 查询学员课程列表
     * @param personId 学员id
     * @param classState  课程状态
     * @param classStartTime 查询课程开始时间
     * @param classEndTime 查询课程结束时间
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 分页数据对象
     * @throws ParseException 转换日期格式错误
     */
    @Override
    public PageInfo<LessonResult> searchLessonPageByPersonId(int personId, Integer classState,String classStartTime, String classEndTime, Integer pageNum, Integer pageSize) throws ParseException {
        if (pageNum==null || pageNum<0){
            pageNum=1;
        }
        if (pageSize==null || pageSize<0){
            pageSize=15;
        }
        PageHelper.startPage(pageNum, pageSize);
        String patterns="yyyy-MM-dd";
        Date startTime=null,endTime=null;
        if (StringUtils.isNotEmpty(classStartTime)){
            startTime=DateUtils.parseDate(classStartTime,patterns);
        }
        if (StringUtils.isNotEmpty(classEndTime)){
            endTime=DateUtils.parseDate(classEndTime,patterns);
        }
        List<LessonResult> list=lessonsMapper.selectLessonPageByPersonId(personId,classState,startTime ,endTime);
        for (LessonResult record:list){
            if (StringUtils.isNotEmpty(record.getMaterialPages())){
                String[] pages=record.getMaterialPages().split(",");
                int pageCount=pages.length;
                if (pageCount>0){
                    record.setMaterialStartPage(pages[0]);
                }
                if (pageCount>2){
                    record.setMaterialPageExtent(pages[0]+"~"+pages[pageCount-1]);
                }else {
                    record.setMaterialPageExtent(record.getMaterialPages());
                }
            }
        }
        return new PageInfo<>(list);
    }

    /**
     * 查询所有课程记录
     * @param record 查询条件
     * @param pageNum 页码
     * @param pageSize 页记录数
     * @return
     */
    @Override
    public PageInfo<LessonResult> searchLessonPage(LessonResult record, Integer pageNum, Integer pageSize) {
        if (pageNum==null || pageNum<0){
            pageNum=1;
        }
        if (pageSize==null || pageSize<0){
            pageSize=15;
        }
        if (record!=null) {
            if (!org.springframework.util.StringUtils.isEmpty(record.getSearchKey())) {
                String[] searchKeyArray=record.getSearchKey().trim().split(" ");
                List<String> listSearchKey=new ArrayList<>(searchKeyArray.length);
                for (String searchKey : searchKeyArray){
                    if (!org.springframework.util.StringUtils.isEmpty(searchKey)){
                        listSearchKey.add(searchKey);
                    }
                }
                if (listSearchKey.size() > 0){
                    record.setListSearchKey(listSearchKey);
                }
            }

            if (!org.springframework.util.StringUtils.isEmpty(record.getSearchTeaKey())) {
                String[] searchKeyArray=record.getSearchTeaKey().trim().split(" ");
                List<String> listSearchKey=new ArrayList<>(searchKeyArray.length);
                for (String searchKey : searchKeyArray){
                    if (!org.springframework.util.StringUtils.isEmpty(searchKey)){
                        listSearchKey.add(searchKey);
                    }
                }
                if (listSearchKey.size() > 0){
                    record.setListTeaSearchKey(listSearchKey);
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);

        List<LessonResult> list=lessonsMapper.selectLessonPage(record);
        for (LessonResult result:list){
            if (StringUtils.isNotEmpty(result.getMaterialPages())){
                String[] pages=result.getMaterialPages().split(",");
                int pageCount=pages.length;
                if (pageCount>2){
                    result.setMaterialPageExtent(pages[0]+"~"+pages[pageCount-1]);
                }else {
                    result.setMaterialPageExtent(result.getMaterialPages());
                }
            }
        }
        return new PageInfo<>(list);
    }

    /**
     * 查询学员对课程的评价列表
     * @param record 查询条件
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 列表
     */
    @Override
    public PageInfo<StudentEvaluationResult> searchLessonStudentEvaluationByPage(StudentEvaluationResult record, int pageNum, int pageSize){
        if (pageNum<0){
            pageNum=1;
        }
        if (pageSize<0){
            pageSize=15;
        }
        /*int roleId=Integer.parseInt(request.getSession().getAttribute("roleId").toString());
        if (roleId==8){
            record.setListSscId(new ArrayList<>(1));
            record.getListSscId().add(Integer.parseInt(request.getSession().getAttribute("userid").toString()));
        }else if (roleId==2){
            record.setListCcId(new ArrayList<>(1));
            record.getListCcId().add(Integer.parseInt(request.getSession().getAttribute("userid").toString()));
        }*/
        PageHelper.startPage(pageNum, pageSize);
        record.setLanguage(this.browserLanguage());
        List<StudentEvaluationResult> list=lessonsMapper.selectStudentEvaluationByPage(record);

        return new PageInfo<>(list);
    }

    /**
     * 获取客户终端使用语言
     * @return
     */
    private String browserLanguage(){
        String language = request.getLocale().getCountry().trim().toLowerCase();
        if (!"cn".equals(language) && !"en".equals(language)) {
            language = "en";
        }
        return language;
    }

    /**
     * 修改官网首页是否显示本节课学员评价
     * @param lessonId 课程id
     * @param show 是否显示标记
     * @return
     */
    @Override
    public int updateLessonShowByLessonId(int lessonId,int show){
        return lessonsMapper.updateLessonShow(lessonId, show);
    }
    /**
     * 查询后台取消课程原因列表
     * @return 原因列表
     */
    @Override
    public List<CancelCourseRecord> searchCancelCourseReasonList(){
        return lessonsMapper.selectCancelReasonList();
    }

    /**
     * 查询调整课程的信息
     * @param lessonId 课程id
     * @return 课程信息
     */
    @Override
    public LessonResult searchChangeLessonInfoByLessonId(int lessonId){
        return lessonsMapper.selectChangeLessonInfoByLessonId(lessonId);
    }

    /**
     * 查询教师基地
     * @return
     */
    @Override
    public List<Map<String,Object>> searchTeacherSiteList(){
        return lessonsMapper.selectTeacherSiteList();
    }

    /**
     * 查询教师级别
     * @return
     */
    @Override
    public List<Map<String,Object>> searchTeacherLevelList(){
        return lessonsMapper.selectTeacherLevelList();
    }

    /**
     * 查询上课方式列表
     * @return
     */
    @Override
    public List<Map<String,Object>> searchClassWayList(){
        return lessonsMapper.selectClassWayList();
    }

    /**
     * 查询调课更换老师原因
     * @return
     */
    @Override
    public List<Map<String,Object>> searchLessonChangeReasonList(){
        return lessonsMapper.selectLessonChangeReasonList();
    }

    /**
     * 查询老师空闲时间表
     * @param teacherLevel 老师级别id
     * @param strDate 查询日期
     * @param groupId 老师组id
     * @param teacherName 老师账号
     * @return
     */
    @Override
    public List<LessonResult> searchTeacherFreeClassTimeList(Integer teacherLevel, String strDate, Integer groupId, String teacherName){
        return lessonsMapper.selectFreeClassTimeByDate(teacherLevel,strDate,groupId,teacherName);
    }

    /**
     * 添加老师投诉学员处理结果
     * @param lessonId 课程id
     * @param result 处理结果
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateTeaComplaintByLessonId(int lessonId, String result){
        int num=lessonsMapper.updateTeaComplaintByLessonId(lessonId, result, request.getSession().getAttribute("loginname").toString());
        if (num>0){
            LessonResult less=lessonsMapper.selectLessonReturnInfoByLessonId(lessonId);
            StudentDynamics sd = new StudentDynamics();
            sd.setAddTime(new Date());
            sd.setAddUser(request.getSession().getAttribute("loginname").toString());
            sd.setPersonId(less.getPersonId());
            sd.setStudentLogin(less.getStudentLogin());
            sd.setAddUserId(Integer.parseInt(request.getSession().getAttribute("userid").toString()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            sd.setContent("【老师投诉】上课时间："+sdf.format(less.getReleaseTime())+"  处理结果 :"+result);
            sd.setQuestionnaireId(0);
            stuDynamicService.addSimpleStudentDynamics(sd);
        }
        return num;
    }

    /**
     * 查询课程老师评价信息
     * @param lessonId 课程id
     * @return
     */
    @Override
    public LessonComments searchCourseCommentsInfo(int lessonId){

        LessonComments lc=lessonsMapper.selectLessonCommentByLessonId(lessonId);
        String language=request.getLocale().getCountry().toLowerCase();
        lc.setLanguage(language);
        if(lc.getStarNum()!=null) {
            //错词本
//            lc.setListKMC(lessonsMapper.selectLessonMistakesByLessonId(lessonId));
            lc.setListKmc(this.searchMistakeWords(lessonId));
            //知识点列表
            lc.setListLJQK(this.getCnKnowledgePointList(lessonId,language));
            //demo学习表现
            lc.setDemoComment(this.searchSelectedNameInfo(lessonId,language));
            if(null==lc.getParticipation() || lc.getParticipation()==0) {
                lc.setListLCP(lessonsMapper.selectClassPerformancesByLessonId(lessonId));
            }else {
                lc.setListAttitudeTag(lessonsMapper.selectAttitudeTags(lessonId));
            }
        }else {
            lc.setPronunciationList(lessonsMapper.selectMistakeWordInfoByLessonId(lessonId,"2"));
            lc.setVocabularyList(lessonsMapper.selectMistakeWordInfoByLessonId(lessonId,"3"));
            lc.setGrammarList(lessonsMapper.selectMistakeWordInfoByLessonId(lessonId,"1"));
//            this.setTeaRank(teaRankService.selectByLessonId(teaRank.getLessonId()));
        }

        return lc;
    }

    private List<Map<String,Object>> getCnKnowledgePointList(Integer lessonId,String language){
        List<TextbookKnowledgePoint> list=lessonsMapper.selectLessonKnowledgePointList(lessonId,language);
        List<Map<String,Object>> result=new ArrayList<>();
        if (list!=null && list.size()>0){
            Map<String,Object> firstMap;
            List<Map<String,Object>> tempList = null;
            Map<String,Object> tempMap;
            int qkId=0;
            for (int i=0;i<list.size();i++){
                if (list.get(i).getId()!=qkId){
                    qkId=list.get(i).getId();
                    firstMap=new HashMap<>(3);
                    firstMap.put("id",list.get(i).getId());
                    firstMap.put("name",list.get(i).getKnowledgeName());
                    tempList=new ArrayList<>();
                    firstMap.put("list",tempList);
                    result.add(firstMap);
                }
                tempMap=new HashMap<>(5);
                tempMap.put("state", list.get(i).getState());

                if (!list.get(i).getKnowledgeThirdName().equals(list.get(i).getKnowledgeSecondName())) {
                    tempMap.put("thirdName", list.get(i).getKnowledgeThirdName());
                }else {
                    tempMap.put("thirdName", "");
                }
                if (!list.get(i).getKnowledgeSecondName().equals(list.get(i).getKnowledgeFirstName())) {
                    tempMap.put("secondName", list.get(i).getKnowledgeSecondName());
                }else {
                    tempMap.put("secondName", "");
                }
                tempMap.put("firstName", list.get(i).getKnowledgeFirstName());

                tempList.add(tempMap);
            }
            list.clear();
        }
        return result;
    }
    /**
     * 获取demo评价后的学术表现
     * @param lessonId 课程id
     * @param language 语言版本
     * @return 结果
     */
    private Map<String,String> searchSelectedNameInfo(Integer lessonId,String language){
        Map<String,String> result=new HashMap<>(5);
        List<Map<String,String>> list=lessonsMapper.selectSelectedNameList(lessonId,language);
        if (list!=null && list.size()>0){
            for (Map<String, String> stringStringMap : list) {
                result.put(stringStringMap.get("key"), stringStringMap.get("name"));
            }
        }
        return result;
    }

    /**
     * 拼接错词本数据
     * @param lessonId 课程id
     * @return
     */
    private List<Map<String, Object>> searchMistakeWords(int lessonId){
        List<Map<String, Object>> listResult = new ArrayList<> ();
        List<LessonKnowledgeMistakesCase> list=lessonsMapper.selectLessonMistakesByLessonId(lessonId);
        String name1="-1",name2="-1",name3="-1";
        List<Map<String,Object>> listName1 = null;
        Map<String, Object> tempName1;
        List<Map<String,Object>> listName2 = null;
        Map<String, Object> tempName2;
        List<Map<String,Object>> listName3 = null;
        Map<String, Object> tempName3;
        for (LessonKnowledgeMistakesCase record:list){
            if (!name1.equals(record.getFirstName())){
                name1=record.getFirstName();
                tempName1=new HashMap<> ();
                tempName1.put("name",name1);
                listName1=new ArrayList<>();
                tempName1.put("list",listName1);
                listResult.add(tempName1);
                name2="-1";
            }
            if (!name2.equals(record.getSecondName())){
                name2=record.getSecondName();
                tempName2=new HashMap<> ();
                tempName2.put("name",name2);
                listName2=new ArrayList<>();
                tempName2.put("list",listName2);
                listName1.add(tempName2);
                name3="-1";
            }
            if (!name3.equals(record.getName())){
                name3=record.getName();
                tempName3=new HashMap<> ();
                tempName3.put("name",name3);
                listName3=new ArrayList<>();
                tempName3.put("list",listName3);
                listName2.add(tempName3);
            }
            Map<String, Object> tempMap=new HashMap<>(2);
            tempMap.put("correctInfo",record.getCorrectInfo());
            tempMap.put("errorInfo",record.getErrorInfo());
            listName3.add(tempMap);
        }
//        System.out.println(JSON.toJSONString(listResult));
        return listResult;
    }
}
